import defaultSettings from '@/settings'
import { useDark, useToggle } from '@vueuse/core'
import { useDynamicTitle } from '@/utils/dynamicTitle'
import { onMounted } from 'vue'

const isDark = useDark()
const toggleDark = useToggle(isDark)
const { sideTheme, showSettings, topNav, tagsView, fixedHeader, sidebarLogo, dynamicTitle } = defaultSettings

const storageSetting = JSON.parse(localStorage.getItem('layout-setting')) || ''

const useSettingsStore = defineStore('settings', {
  state: () => ({
    title: '',
    theme: storageSetting.theme || '#409EFF',
    sideTheme: storageSetting.sideTheme || sideTheme,
    showSettings: showSettings,
    topNav: storageSetting.topNav === undefined ? topNav : storageSetting.topNav,
    tagsView: storageSetting.tagsView === undefined ? tagsView : storageSetting.tagsView,
    fixedHeader: storageSetting.fixedHeader === undefined ? fixedHeader : storageSetting.fixedHeader,
    sidebarLogo: storageSetting.sidebarLogo === undefined ? sidebarLogo : storageSetting.sidebarLogo,
    dynamicTitle: storageSetting.dynamicTitle === undefined ? dynamicTitle : storageSetting.dynamicTitle,
    isDark: isDark.value,
    isEyeProtection: JSON.parse(localStorage.getItem('isEyeProtection')) || false
  }),
  actions: {
    // 修改布局设置
    changeSetting(data) {
      const { key, value } = data
      if (this.hasOwnProperty(key)) {
        this[key] = value
      }
    },
    // 设置网页标题
    setTitle(title) {
      this.title = title
      useDynamicTitle()
    },
    // 切换暗黑模式
    toggleTheme() {
      this.isDark = !this.isDark
      toggleDark()
    },
    // 切换护眼模式
    // toggleEyeProtection() {
    //   let isEyeProtection = JSON.parse(localStorage.getItem('isEyeProtection'))
    //   if (!isEyeProtection) isEyeProtection = this.isEyeProtection
    //   isEyeProtection = !isEyeProtection
    //   if (isEyeProtection) {
    //     // 给html添加class类为eyeProtection
    //     document.documentElement.classList.toggle('eyeProtection', isEyeProtection)
    //   } else {
    //     // 给html删除class类为eyeProtection
    //     document.documentElement.classList.remove('eyeProtection')
    //   }
    //   localStorage.setItem('isEyeProtection', isEyeProtection)
    // },
    toggleEyeProtection() {
      this.isEyeProtection = !this.isEyeProtection
      if (this.isEyeProtection) {
        // 给html添加class类为eyeProtection
        document.documentElement.classList.add('eyeProtection')
      } else {
        // 给html删除class类为eyeProtection
        document.documentElement.classList.remove('eyeProtection')
      }
      localStorage.setItem('isEyeProtection', this.isEyeProtection)
    }
  }
})
export default useSettingsStore
